<template>
  <div class="transfer-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="转出仓库">
          <el-select v-model="searchForm.fromWarehouseId" placeholder="请选择转出仓库" clearable style="width: 200px">
            <el-option
              v-for="wh in warehouseList"
              :key="wh.id"
              :label="wh.name || wh.warehouseName"
              :value="wh.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转入仓库">
          <el-select v-model="searchForm.toWarehouseId" placeholder="请选择转入仓库" clearable style="width: 200px">
            <el-option
              v-for="wh in warehouseList"
              :key="wh.id"
              :label="wh.name || wh.warehouseName"
              :value="wh.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总转账金额</div>
            <div class="stats-value">¥{{ stats.totalAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">本月转账</div>
            <div class="stats-value">¥{{ stats.monthlyAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">待审核</div>
            <div class="stats-value">{{ stats.pendingCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已审核</div>
            <div class="stats-value">{{ stats.approvedCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增转账单</el-button>
      <el-button type="success" @click="handleBatchApprove" :disabled="!selectedIds.length">批量审核</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">批量删除</el-button>
      <el-button type="warning" @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">资金转账单管理</div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">新增转账单</el-button>
          <el-button type="success" @click="handleBatchApprove" :disabled="!selectedIds.length">批量审核</el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">批量删除</el-button>
        </div>
      </div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="Array.isArray(tableData) ? tableData : []"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="transferNo" label="单据编号" width="180" />
        <el-table-column prop="fromWarehouseId" label="转出仓库" width="150">
          <template #default="{ row }">
            {{ getWarehouseName(row.fromWarehouseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="toWarehouseId" label="转入仓库" width="150">
          <template #default="{ row }">
            {{ getWarehouseName(row.toWarehouseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="转账金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="transferDate" label="转账日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.transferDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button v-if="row.status === 0" type="success" size="small" @click="handleApprove(row)">审核</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增转账单' : dialogType === 'edit' ? '编辑转账单' : '查看转账单'"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="单据编号" prop="transferNo">
          <el-input v-model="form.transferNo" placeholder="请输入单据编号">
            <template #append>
              <el-button @click="generateBillNo" :disabled="dialogType === 'view'">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="转出仓库" prop="fromWarehouseId">
          <el-select v-model="form.fromWarehouseId" placeholder="请选择转出仓库" style="width: 100%">
            <el-option
              v-for="wh in warehouseList"
              :key="wh.id"
              :label="wh.name || wh.warehouseName"
              :value="wh.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转入仓库" prop="toWarehouseId">
          <el-select v-model="form.toWarehouseId" placeholder="请选择转入仓库" style="width: 100%">
            <el-option
              v-for="wh in warehouseList"
              :key="wh.id"
              :label="wh.name || wh.warehouseName"
              :value="wh.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转账金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入转账金额" type="number" step="0.01">
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="转账日期" prop="transferDate">
          <el-date-picker
            v-model="form.transferDate"
            type="date"
            placeholder="请选择转账日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTransferOrderList as getTransferList,
  addTransferOrder as addTransfer,
  updateTransferOrder as updateTransfer,
  deleteTransferOrder as deleteTransfer,
  approveTransferOrder as approveTransfer,
  batchDeleteTransferOrder as batchDeleteTransfer,
  getTransferOrderStats as getTransferStats,
  exportTransferOrder as exportTransfer
} from '@/api/finance/transferOrder'
import { getWarehouseList } from '@/api/warehouse/warehouse'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add') // add, edit, view
const formRef = ref(null)
const warehouseList = ref([])
const stats = reactive({
  totalAmount: '0.00',
  monthlyAmount: '0.00',
  pendingCount: 0,
  approvedCount: 0
})

// 统计数据
const totalTransfer = ref(0)

// 搜索表单
const searchForm = reactive({
  fromWarehouseId: '',
  toWarehouseId: '',
  status: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  transferNo: '',
  fromWarehouseId: '',
  toWarehouseId: '',
  amount: '',
  transferDate: '',
  status: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  transferNo: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
  fromWarehouseId: [{ required: true, message: '请选择转出仓库', trigger: 'change' }],
  toWarehouseId: [{ required: true, message: '请选择转入仓库', trigger: 'change' }],
  amount: [{ required: true, message: '请输入转账金额', trigger: 'blur' }],
  transferDate: [{ required: true, message: '请选择转账日期', trigger: 'change' }]
}

// 获取账户列表
const loadWarehouseList = async () => {
  try {
    const list = await getWarehouseList()
    warehouseList.value = Array.isArray(list) ? list : []
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 根据账户ID获取账户名称
const getWarehouseName = (warehouseId) => {
  const wh = warehouseList.value.find(item => item.id === warehouseId)
  return wh ? (wh.name || wh.warehouseName || warehouseId) : warehouseId
}

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    
    const response = await getTransferList(params)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else if (response && response.records) {
      // 直接Page格式（兼容性）
      tableData.value = response.records || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取转账单数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const response = await getTransferStats()
    
    let data
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      data = response.data
    } else if (response && response.records !== undefined) {
      // 直接数据格式（兼容性）
      data = response
    } else {
      console.error('统计数据响应格式错误:', response)
      data = { records: [] }
    }
    
    const records = Array.isArray(data?.records) ? data.records : []
    // 计算统计数据
    const totalAmount = records.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0)
    const currentMonth = new Date().getMonth() + 1
    const currentYear = new Date().getFullYear()
    const monthlyAmount = records.reduce((sum, item) => {
      if (item.transferDate) {
        const transferDate = new Date(item.transferDate)
        if (transferDate.getMonth() + 1 === currentMonth && transferDate.getFullYear() === currentYear) {
          return sum + (parseFloat(item.amount) || 0)
        }
      }
      return sum
    }, 0)
    const pendingCount = records.filter(item => item.status === 0).length
    const approvedCount = records.filter(item => item.status === 1).length
    
    // 更新totalTransfer变量
    totalTransfer.value = totalAmount
    
    Object.assign(stats, {
      totalAmount: totalAmount.toFixed(2),
      monthlyAmount: monthlyAmount.toFixed(2),
      pendingCount,
      approvedCount
    })
  } catch (error) {
    console.error('获取统计数据失败:', error)
    Object.assign(stats, {
      totalAmount: '0.00',
      monthlyAmount: '0.00',
      pendingCount: 0,
      approvedCount: 0
    })
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    fromWarehouseId: '',
    toWarehouseId: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}
const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = async () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
  await generateBillNo()
}
// 查看
const handleView = (row) => {
  dialogType.value = 'view'
  Object.assign(form, row)
  dialogVisible.value = true
}
// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}
// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条转账单吗？', '提示', { type: 'warning' })
    await deleteTransfer(row.id)
    ElMessage.success('删除成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除转账单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}
// 审核
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核这条转账单吗？', '提示', { type: 'warning' })
    await approveTransfer(row.id)
    ElMessage.success('审核成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核转账单失败:', error)
      ElMessage.error('审核失败')
    }
  }
}
// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的转账单')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条转账单吗？`, '提示', { type: 'warning' })
    await batchDeleteTransfer(selectedIds.value)
    ElMessage.success('批量删除成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除转账单失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}
// 批量审核
const handleBatchApprove = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要审核的转账单')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要审核选中的 ${selectedIds.value.length} 条转账单吗？`, '提示', { type: 'warning' })
    await Promise.all(selectedIds.value.map(id => approveTransfer(id)))
    ElMessage.success('批量审核成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核转账单失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}
// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addTransfer(form)
    } else {
      await updateTransfer(form)
    }
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadData()
    loadStats()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}
// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    transferNo: '',
    fromWarehouseId: '',
    toWarehouseId: '',
    amount: '',
    transferDate: '',
    status: 0,
    remark: ''
  })
}
// 自动生成单据编号
const generateBillNo = async () => {
  try {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    const today = `${year}-${month}-${day}`
    const params = {
      pageNum: 1,
      pageSize: 1000,
      startDate: today,
      endDate: today
    }
    const page = await getTransferList(params)
    const todayRecords = page?.records || []
    const todayCount = todayRecords.length + 1
    const sequence = String(todayCount).padStart(3, '0')
    const billNo = `ZZ${dateStr}${sequence}`
    form.transferNo = billNo
    ElMessage.success('单据编号生成成功')
  } catch (error) {
    console.error('生成单据编号失败:', error)
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    const timestamp = Date.now().toString().slice(-3)
    const billNo = `ZZ${dateStr}${timestamp}`
    form.transferNo = billNo
    ElMessage.success('单据编号生成成功')
  }
}
// 导出
const handleExport = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出转账管理数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['转账单号', '转出仓库', '转入仓库', '金额', '转账日期', '状态', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.transferNo || '',
        row.fromWarehouse || '',
        row.toWarehouse || '',
        row.amount || 0,
        row.transferDate || '',
        getStatusText(row.status),
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      totalTransfer.value || 0,
      '',
      `记录数: ${pagination.total || 0}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `转账管理数据_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}
// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const mm = String(d.getMinutes()).padStart(2, '0')
  const ss = String(d.getSeconds()).padStart(2, '0')
  return `${y}-${m}-${day} ${hh}:${mm}:${ss}`
}
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return parseFloat(amount).toFixed(2)
}
const getStatusType = (status) => {
  const statusMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return statusMap[status] || 'info'
}
const getStatusText = (status) => {
  const statusMap = { 0: '待审核', 1: '已审核', 2: '已拒绝' }
  return statusMap[status] || '未知'
}
onMounted(() => {
  loadWarehouseList()
  loadData()
  loadStats()
})
</script>

<style scoped>
.transfer-container { padding: 20px; }
.search-card { margin-bottom: 20px; }
.stats-row { margin-bottom: 20px; }
.stats-card { text-align: center; }
.stats-item { padding: 10px; }
.stats-title { font-size: 14px; color: #666; margin-bottom: 8px; }
.stats-value { font-size: 24px; font-weight: bold; color: #409eff; }
.table-card { margin-bottom: 20px; }
.table-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.table-title { font-size: 18px; font-weight: bold; }
.table-actions { display: flex; gap: 10px; }
.pagination-container { margin-top: 20px; text-align: right; }
</style> 